"""
    功能: txt日志文件合并工具
    版本: 1.0
    作者: 程序员karai
    日期: 2023年07月01日

    日志: 当前版本只支持选择文件夹
"""

from ast import List, Not
from cProfile import label
from cgitb import text
from concurrent.futures.thread import _worker
from inspect import findsource
from io import TextIOWrapper
from math import exp
from ntpath import isdir
import os
from re import T
from threading import Thread
from time import sleep, time
import tkinter
from tkinter import font
from tkinter.constants import NONE
from tkinter.font import Font
import ttkbootstrap as ttk;
from turtle import title
from typing import Text

from ttkbootstrap.dialogs import Messagebox
from ttkbootstrap.style import OUTLINE
from tkinter import filedialog,dialog,messagebox
from pathlib import Path
SUPPORT_FILE_TYPE = [".txt" , ".log", ".text",""]

app = tkinter.Tk()
screen_width = app.winfo_screenwidth()
screen_height = app.winfo_screenheight()
x = (screen_width - 300) // 2
y = (screen_height - 471) // 2
app.geometry(f"300x471+{x}+{y}")
app.wm_title("日志文件合并工具")
app.resizable(False,False)
app.attributes('-topmost', True)  # 置顶显示
# 设置图标
app.iconbitmap("favicon.ico")

"""
 ===================================  样式 开始 ===================================
"""
selectorBtnStyle = ttk.Style()
mergeOuputInfoStyle = ttk.Style()
start_btn = ttk.Style();
selectorBtnStyle.configure("Black.TButton",
                background="#789",    
                borderwidth=0,
                bordercolor="#789",
                OUTLINE="none",
                focuscolor="none",
                foreground="#fff") 

selectorBtnStyle.map("Black.TButton",
          background=[("active", "#567"),  
                      ("!active", "#789")])

start_btn.configure("Start.TButton",
                background="#789",    
                borderwidth=0,
                bordercolor="#789",
                OUTLINE="none",
                focuscolor="none",
                foreground="#fff") 

start_btn.map("Start.TButton",
          background=[("active", "#567"),  
                      ("!active", "#789")])

"""
 ===================================  样式 结束 ===================================
"""



path_var = ttk.StringVar();

rest_file_prefix = "日志合成工具_";
rest_file_path ="",




selectorPanel = ttk.LabelFrame(text="选择日志文件夹",width=260,height=60)
selectorBtn = ttk.Button(selectorPanel , text="选择",style="Black.TButton")
start_btn = ttk.Button( text="开始合并",style="Start.TButton",width=260,padding=10)

selectorPathInput = ttk.Entry(selectorPanel,textvariable=path_var )

selectorPathInput.pack(side="left" ,anchor="nw",pady=2,padx=10)
selectorBtn.pack(side="right" , anchor="nw" ,pady=3, padx= 8)
start_btn.pack(side="bottom" , anchor="nw" ,pady=10, padx= 20)

mergeOuputInfo = ttk.Text(
    width=180,
    borderwidth=0,
    height=300,
    highlightthickness=0,
    relief="flat",
    takefocus=0,
    state="disabled",
    font=("宋体",8)

)


selectorPanel.pack_propagate(False) 
selectorPanel.pack( side ="top"  , anchor="nw", padx=20,pady=20)

mergeOuputInfo.pack_propagate(False)
mergeOuputInfo.pack(side="top" , anchor="nw",expand=True,padx=20,pady=10)



"""
选择需要生成的日志文件所在文件夹 
"""
def selectFile():
    mergeOuputInfo.config(state="normal")
    mergeOuputInfo.delete("1.0","end")
    mergeOuputInfo.config(state="disabled")
    selector_dir_path = filedialog.askdirectory(title="合并日志文件")
    if(selector_dir_path is None or selector_dir_path == ""):
        messagebox.showerror(message="路径不能为空",title="选择失败");
        return;
    #print('选择的文件夹路径 : ' + selector_dir_path);
    path_var.set(selector_dir_path)
    fileName = rest_file_prefix + str(time()) + ".txt"
    rest_file_path = selector_dir_path + "/" + rest_file_prefix + str(time()) + ".txt";
    t = Thread(target=preMergeLogFile,daemon=True,args=(selector_dir_path,rest_file_path,fileName,));
    t.start()
  
        

def startBtnEvent():
    fileName = rest_file_prefix + str(time()) + ".txt"
    print("path_var : " + path_var.get())
    rest_file_path = path_var.get() + "/" + rest_file_prefix + str(time()) + ".txt";
    t = Thread(target=preMergeLogFile,daemon=True,args=(path_var.get(),rest_file_path,fileName,));
    t.start()

"""
生成结果文件 并且准备去合并文件
"""

def preMergeLogFile(path, rest_file_path, finalRestFileName):
    try:
        with open(rest_file_path, "w+", encoding="utf-8") as rest_file:
            mergeOuputInfo.config(state="normal")
            mergeOuputInfo.insert("1.0","开始合并...")
            mergeOuputInfo.config(state="disabled")
            sleep(1)
            mergeLogFile(path, rest_file, finalRestFileName)
        messagebox.showinfo(title="合并成功",message=f"日志合并完成.. 合并后的文件在 {rest_file_path}")
    except Exception as e:
        messagebox.showerror(message=str(e))
        
"""
 合并文件
"""
def mergeLogFile(path,rest_file,finalRestFileName):
    try :
     floder =  Path(path)
     for file in floder.iterdir():
        if file.is_file():
            if  file.name != finalRestFileName and file.suffix in SUPPORT_FILE_TYPE :
                # print(file.suffix)
                doResultFile(file.absolute().__str__(),file.name,rest_file);
        elif file.is_dir():
             mergeLogFile(file.absolute(),rest_file,finalRestFileName)
    except Exception as e:
       messagebox.showerror(message=e.__str__());
    #    t.join();
       




# 去创建文件
def doResultFile(filePath, fileName ,rest_file : TextIOWrapper):
   rest_file.writelines(f"=============={fileName} start==============\n\n")
   with open(filePath, "r", encoding="utf-8") as f:
    content = f.readlines()
    rest_file.writelines(content);
   rest_file.writelines("\n");
   rest_file.writelines(f"=============={fileName} end ==============\n\n")
   mergeOuputInfo.config(state="normal")
   mergeOuputInfo.insert(index="2.0",chars=fileName + "合并完成...")
   mergeOuputInfo.insert(index="2.0" , chars="\n");
   mergeOuputInfo.see("end")
   mergeOuputInfo.config(state="disabled")




selectorBtn.bind("<Button-1>",lambda event:selectFile())
start_btn.bind("<Button-1>" , lambda event:startBtnEvent())


app.mainloop()